package com.leTest.controller;

import com.leTest.R;
import com.leTest.service.MsmService;
import com.leTest.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/eduMsm/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //1.从redis中获取验证码,如果能取到就不需要使用阿里云发送验证码,我们直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //生成4位随机数字
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);

        //调用service中发送短信的方法
        boolean isSend = msmService.send(param, phone);

        //2.如果不能从redis中获取到,就使用阿里云发送验证码
        if (isSend) {//发送成功,把发送成功的验证码放到redis里面并且设置有效时长
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);

            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }


}

